#include <QDebug>
#include <QPushButton>
#include <QStringBuilder>
#include <QFile>
#include <QFileInfo>
#include "CreateClassForm.h"
#include "Template.h"
#include "Include/Project.h"
#include "ui_CreateClassForm.h"

CreateClassForm::CreateClassForm(const QString& path, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::CreateClassForm),
    _path(path)
{
    ui->setupUi(this);
    ui->lblPath->setText(_path);

    ui->edtClassFile->setBasePath(path);
    ui->edtClassFile->setExtension("py");

    ui->edtUiFile->setBasePath(path);
    ui->edtUiFile->setExtension("ui");

    ui->edtUiGenFile->setBasePath(path);
    ui->edtUiGenFile->setExtension("py");

    ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);

    ui->cmdKind->addItems(QStringList() << "QDialog" << "QWidget" << "QMainMindow");

    connect(ui->edtClassName, SIGNAL(textChanged(QString)), SLOT(onTextChanged(QString)));
    connect(ui->buttonBox, SIGNAL(accepted()), SLOT(onAccepted()));
}

CreateClassForm::~CreateClassForm()
{
    delete ui;
}

void CreateClassForm::onTextChanged(const QString & text)
{
    ui->edtClassFile->setBaseName(text);
    ui->edtUiFile->setBaseName(text);
    ui->edtUiGenFile->setBaseName("Ui_" % text);
    ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(
                !ui->edtClassFile->exists() &&
                !ui->edtUiFile->exists() &&
                !ui->edtUiGenFile->exists()
    );
}

void CreateClassForm::onAccepted()
{
    QString kind = ui->cmdKind->currentText();

    Template tmpl("class-form");
    QMap<QString, QString> items;
    items["class-name"] = ui->edtClassName->text();
    items["class-parent"] = kind;
    items["ui-class-name"] = QFileInfo(ui->edtUiGenFile->fullFileName()).baseName();
    items["import"] = Plugins::Project::currentInstance()->guiVersion() % ".QtGui";
    QFile file(ui->edtClassFile->fullFileName());
    if (file.open(QIODevice::WriteOnly)){
        file.write(tmpl.Render(items).toUtf8());
        file.close();
    }

    QString uiName = "qtform-" % kind;
    if (kind != "QDialog" && kind != "QWidget" && kind != "QMainWindow")
        uiName = "qtform-QWidget";

    Template uiTmpl(uiName);
    QFile uifile(ui->edtUiFile->fullFileName());
    if (uifile.open(QIODevice::WriteOnly)){
        uifile.write(uiTmpl.Render(items).toUtf8());
        uifile.close();
    }

    accept();
}

QStringList CreateClassForm::openAfter()
{
    return QStringList() << ui->edtClassFile->fullFileName() << ui->edtUiFile->fullFileName();
}
